<template>
  <div class="viewshed-ui">
    <!-- 左上角操作区 -->
    <div class="viewshed-toolbar">
      <button @click="drawViewShed">绘制可视域</button>
      <!--      <button @click="drawClip">绘制裁剪面</button>-->
      <button @click="clear">清除</button>
      <!--      <div style="margin-top: 10px">-->
      <!--        裁剪模式：-->
      <!--        <select v-model="clipMode">-->
      <!--          <option value="keep">保留区域内</option>-->
      <!--          <option value="remove">移除区域内</option>-->
      <!--        </select>-->
      <!--      </div>-->
    </div>
    <!-- 右侧属性编辑区 -->
    <div class="viewshed-panel">
      <h3>属性编辑</h3>
      <div class="form-group">
        <label>方向(度)</label>
        <input type="range" min="0" max="360" step="0.1" v-model.number="params.direction" @input="updateParams" />
        <input type="number" v-model.number="params.direction" @input="updateParams" />
      </div>
      <div class="form-group">
        <label>翻转(度)</label>
        <input type="range" min="-90" max="90" step="0.1" v-model.number="params.pitch" @input="updateParams" />
        <input type="number" v-model.number="params.pitch" @input="updateParams" />
      </div>
      <div class="form-group">
        <label>距离(米)</label>
        <input type="range" min="1" max="5000" step="1" v-model.number="params.distance" @input="updateParams" />
        <input type="number" v-model.number="params.distance" @input="updateParams" />
      </div>
      <div class="form-group">
        <label>水平视场角(度)</label>
        <input type="range" min="1" max="120" step="1" v-model.number="params.horizontalFov" @input="updateParams" />
        <input type="number" v-model.number="params.horizontalFov" @input="updateParams" />
      </div>
      <div class="form-group">
        <label>垂直视场角(度)</label>
        <input type="range" min="1" max="90" step="1" v-model.number="params.verticalFov" @input="updateParams" />
        <input type="number" v-model.number="params.verticalFov" @input="updateParams" />
      </div>
      <div class="form-group">
        <label>可见区颜色</label>
        <input
          type="color"
          :value="colorToHex(params.visibleAreaColor)"
          @input="(e) => onColorChange('visibleAreaColor', (e.target as HTMLInputElement).value)"
        />
      </div>
      <div class="form-group">
        <label>不可见区颜色</label>
        <input
          type="color"
          :value="colorToHex(params.hiddenAreaColor)"
          @input="(e) => onColorChange('hiddenAreaColor', (e.target as HTMLInputElement).value)"
        />
      </div>
      <div style="margin-top: 10px">本例中观察者附加高度：1.8 米</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { AnalysisTools, AnalysisType } from '@/utils/analysis/AnalysisTools';
import { ViewShedAnalysis } from '@/utils/analysis/impl/ViewShedAnalysis';

// 父组件传入 analysisTools 实例
const props = defineProps<{ analysisTools: AnalysisTools }>();

// 可视域参数，全部响应式
const params = reactive({
  direction: 0,
  pitch: 0,
  distance: 1000,
  horizontalFov: 90,
  verticalFov: 60,
  visibleAreaColor: 'rgba(0, 255, 0, 1)', // 绿色
  hiddenAreaColor: 'rgba(255, 0, 0, 1)', // 红色
});

// const direction = ref(0);
// const pitch = ref(0);
// const distance = ref(1000);
// const horizontalFov = ref(90);
// const verticalFov = ref(60);
// const visibleAreaColor = ref('rgba(0, 255, 0, 1)');
// const hiddenAreaColor = ref('rgba(255, 0, 0, 1)');

const clipMode = ref('keep');

// 工具函数：获取当前可视域分析实例
function getCurrentViewShedInstance() {
  return (props.analysisTools.analysisMap.get(AnalysisType.ViewShed) as ViewShedAnalysis) || null;
}

// 工具函数：rgba转16进制色值（用于input[type=color]）
function colorToHex(rgba: string): string {
  // 只取rgb部分
  const match = rgba.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
  if (!match) return '#00ff00';
  const r = parseInt(match[1]).toString(16).padStart(2, '0');
  const g = parseInt(match[2]).toString(16).padStart(2, '0');
  const b = parseInt(match[3]).toString(16).padStart(2, '0');
  return `#${r}${g}${b}`;
}

// 颜色选择器变更时，转为rgba字符串
function onColorChange(key: 'visibleAreaColor' | 'hiddenAreaColor', hex: string) {
  // 保持不透明度为1
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  params[key] = `rgba(${r}, ${g}, ${b}, 1)`;
  updateParams();
}

// 属性变更时，自动同步到分析实例
function updateParams() {
  const instance = getCurrentViewShedInstance();
  // console.log('[ViewShedPanel.updateParams] 获取到的ViewShedAnalysis实例:', instance, '当前参数:', { ...params });
  if (instance) {
    // instance.setParams({ ...toRaw(params) });
    // instance.setParams(JSON.parse(JSON.stringify(params)));
    // instance.setParams({
    //   direction: direction.value,
    //   pitch: pitch.value,
    //   distance: distance.value,
    //   horizontalFov: horizontalFov.value,
    //   verticalFov: verticalFov.value,
    //   visibleAreaColor: visibleAreaColor.value,
    //   hiddenAreaColor: hiddenAreaColor.value,
    // });
  } else {
    // console.warn('[ViewShedPanel.updateParams] 未获取到ViewShedAnalysis实例');
  }
}

// 绘制可视域（激活分析并同步参数）
async function drawViewShed() {
  await props.analysisTools.activate(AnalysisType.ViewShed);
  updateParams();
}

// 绘制裁剪面（可根据实际需求补充）
function drawClip() {
  // TODO: 裁剪面相关逻辑
}

// 清除分析
function clear() {
  props.analysisTools.clearAll();
}
</script>

<style scoped>
.viewshed-ui {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.viewshed-toolbar {
  position: absolute;
  top: 20px;
  left: 20px;
  background: #222c;
  color: #fff;
  padding: 16px;
  border-radius: 8px;
  z-index: 10;
  min-width: 260px;
}

.viewshed-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 18px 20px;
  width: 280px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  font-size: 14px;
}

.form-group {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

label {
  min-width: 90px;
}

input[type='range'] {
  flex: 1;
}

input[type='number'] {
  width: 70px;
}
</style>
